package com.example.demo.interceptors;

import com.example.demo.constant.RedisKey;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate; //报错信息错误，无影响

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);

            Long id = Long.parseLong(claims.get("id").toString());

            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

            String key = RedisKey.ADMIN_PREFIX + id;
            String redisToken = operations.get(key);

            if (!redisToken.equals(token)) {
                throw new RuntimeException();
            }

            ThreadLocalUtil.set(claims);

            stringRedisTemplate.expire(key, 7, TimeUnit.DAYS);
        } catch (Exception exception) {
            response.setStatus(401);
            response.setCharacterEncoding("UTF-8");  // 设置字符编码
            response.getWriter().write("未提供有效的管理员token");
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
